package com.gsj.system.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gsj.system.eneity.Client;
import com.gsj.system.eneity.User;
import com.gsj.system.mapper.ClientMapper;
import com.gsj.system.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: clms-eighth
 * @description: 自定义realm
 * @author: 刘守霖
 * @create: 2021-07-17 15:20
 **/

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String s = token.getPrincipal().toString();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",s);
        wrapper.eq("status",0);
        QueryWrapper<Client> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("username",s);
        wrapper2.eq("status",0);
        User user = userMapper.selectOne(wrapper);
        Client client = clientMapper.selectOne(wrapper2);

        if (user!=null){
            ByteSource salt= ByteSource.Util.bytes("efdd1d36-2430-4");
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
            return info;
        }else if(client!=null){
            ByteSource salt= ByteSource.Util.bytes(client.getPwSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(client,client.getPassword(),salt,this.getName());
            return info;
        }
        return null;
    }
}
